package com.xulu.romance.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.pojo.User;
import com.xulu.romance.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtil {


    private static UserService staticUserService;
    private static String userId;
    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }


    /**
     * 生成Token
     */
    public static String getToken(String userId,String userName) {
        return JWT.create()
                .withAudience(userId,userName)  // 用户id作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))  // 两小时过期
                .sign(Algorithm.HMAC256(Constant.SIGNATURE));  // 哈希值作为秘钥
    }

    public static User getUserInfo() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(userId);
            }
        } catch (JWTDecodeException e) {
            return null;
        }


        return null;
    }

    public static Integer getUserId(){

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
               String userId = JWT.decode(token).getAudience().get(0);
                return Integer.valueOf(userId);
            }
        } catch (JWTDecodeException e) {
            return null;
        }

        return null;
    }
    public static String getUserName(){

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                return JWT.decode(token).getAudience().get(1);
            }
        } catch (JWTDecodeException e) {
            return null;
        }

        return null;
    }

}
